package com.huazai.forkjoin;

import java.util.concurrent.*;

/**
 * @author huazai
 * @date 2024/2/20
 */
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        final ForkJoinTask<Integer> submit = forkJoinPool.submit(myTask);
        final Integer result = submit.get();
        forkJoinPool.shutdown();
        System.out.println("result = " + result);
    }
}

class MyTask extends RecursiveTask<Integer> {

    /**
     * 数据开始结束
     */
    private int begin;
    private int end;
    /**
     * 计算结果
     */
    private int result;
    /**
     * 拆分数据，最大值和最小值的差值必须小于VALUE
     */
    private static final int VALUE = 10;


    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - begin) < VALUE) {
            for (int i = begin; i <= end; i++) {
                result += i;
            }
            return result;
        } else {
            int middle = (begin + end) / 2;
            MyTask task01 = new MyTask(begin, middle);
            MyTask task02 = new MyTask(middle + 1, end);
            task01.fork();
            task02.fork();
            return task01.join() + task02.join();
        }
    }
}
